<?php
/**
 * APP消息推送.
 * User: dxk
 * Date: 2021-01-04
 */
namespace App\Service\AppPush;

use App\Library\Service\AliCloud\AppPush;
use App\Traits\SingleInstanceTrait;

class AppPushService
{
    use SingleInstanceTrait;

    const NOTICE_PATIENT_CASE_OVER = 'patient_case_over';//问诊结束

    /**
     * 获取用户别名
     * @param $alicloud_app_key
     * @param $user_id
     * @return string
     */
    public function getUserAlias($alicloud_app_key, $user_id): string
    {
        return trim(\App::environment() . ':user:' . $alicloud_app_key . ':' . $user_id);
    }

    /**
     * 推送通知给用户，每次不超过1000个用户
     * @param array $user_ids
     * @param string $title 消息的标题
     * @param string $body 消息的内容
     * @param array $AndroidExtParameters 通知的扩展属性
     * @param array $iOSExtParameters IOS通知扩展属性
     * @return array
     */
    public function pushNoticeToUsers(array $user_ids, string $title, string $body, array $AndroidExtParameters, array $iOSExtParameters): array
    {
        //先推送给安卓渠道
        $alicloud_app_key = config('sys.aliyun.msg_push.android.appKey');
        $targets = [];
        foreach ($user_ids as $user_id) {
            $targets[] = $this->getUserAlias($alicloud_app_key, $user_id);
        }
        $AppPush = (new AppPush($alicloud_app_key));
        $options = [
            'Title' => $title,
            'Body' => $body,
            'PushType' => 'NOTICE',
            'DeviceType' => 'ANDROID',
            'Target' => 'ALIAS',
            'TargetValue' => implode(',', $targets),
            'StoreOffline' => true,
            'AndroidNotifyType' => 'BOTH',
            'AndroidOpenType' => 'ACTIVITY',
            'AndroidActivity' => 'com.zxkj.iotplant',
            'AndroidExtParameters' => json_encode($AndroidExtParameters),
            'AndroidNotificationChannel' => 1,
        ];
        $android_res = $AppPush->Push($options);
        //推送给IOS渠道
        $alicloud_app_key = config('sys.aliyun.msg_push.ios.appKey');
        $targets = [];
        foreach ($user_ids as $user_id) {
            $targets[] = $this->getUserAlias($alicloud_app_key, $user_id);
        }
        $AppPush = (new AppPush($alicloud_app_key));
        $options = [
            'Title' => $title,
            'Body' => $body,
            'PushType' => 'NOTICE',
            'DeviceType' => 'iOS',
            'Target' => 'ALIAS',
            'TargetValue' => implode(',', $targets),
            'StoreOffline' => true,
            'iOSApnsEnv' => 'PRODUCT',
            'iOSRemindBody' => $body,
            'iOSExtParameters' => json_encode($iOSExtParameters),
        ];
        $ios_res = $AppPush->Push($options);
        return ['android_res' => $android_res, 'ios_res' => $ios_res];
    }
}
